package online.heycm.rbac.domain.basic.repository;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import online.heycm.platform.common.entity.result.Optional;
import online.heycm.rbac.common.constant.ErrorCode;
import online.heycm.rbac.domain.basic.repository.entity.BasicGeneratorIds;
import online.heycm.rbac.domain.basic.repository.mapper.BasicGeneratorIdsMapper;
import org.springframework.context.annotation.Primary;
import org.springframework.stereotype.Component;

/**
 * ID生成器
 *
 * @author hey
 * @version 1.0
 * @date 2024/1/17 9:01
 */
@Component
@Primary
public class IdGeneratorRepository extends ServiceImpl<BasicGeneratorIdsMapper, BasicGeneratorIds> {

    /**
     * 获取下一组序列ID
     *
     * @param idKey ID键
     * @return
     */
    public Optional<BasicGeneratorIds> acquireId(String idKey) {
        // 加乐观锁，尝试3次取ID
        int retry = 3;
        while (retry-- > 0) {
            BasicGeneratorIds generatorIds = this.baseMapper.selectById(idKey);
            if (generatorIds == null) {
                return Optional.error(ErrorCode.GENERATOR_ID);
            }
            boolean ok = this.baseMapper.updateByOptimisticLock(generatorIds) > 0;
            if (ok) {
                return Optional.of(generatorIds);
            }
        }
        return Optional.error(ErrorCode.GENERATOR_ID);
    }

}
